﻿/*    
    This file is part of d-mixr.

    d-mixr is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    d-mixr is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with d-mixr.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using Dmixr.ViewModel;
using System.IO;
using System.Xml.Serialization;

namespace Dmixr
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            AudioSystem.Init();

            MainWindow window = new MainWindow();

            MainWindowViewModel vm = null;

            string prefPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            prefPath += "\\d-mxr_Pref.xml";
            try
            {
                TextReader textReader = new StreamReader(Dmixr.Preferences.GetPreferenceFile() );
                XmlSerializer deserializer = new XmlSerializer(typeof(MainWindowViewModel));
                vm = (MainWindowViewModel)deserializer.Deserialize(textReader);
                vm.Relive();
                textReader.Close();
            }
            catch
            {
                vm = new MainWindowViewModel();
            }

            var viewModel = vm;


            // When the ViewModel asks to be closed, 
            // close the window.
            EventHandler handler = null;
            handler = delegate
            {
                viewModel.RequestClose -= handler;
                window.Close();
            };
            viewModel.RequestClose += handler;

            // Allow all controls in the window to 
            // bind to the ViewModel by setting the 
            // DataContext, which propagates down 
            // the element tree.
            window.DataContext = viewModel;

            window.Show();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            AudioSystem.Term();
        }
    }
}
